using Roots.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace Roots
{
    public class ScoreManager : MonoBehaviour
    {
        [SerializeField] UiHandler ui;

        [SerializeField]
        private int[] resources = new int[] { 30, 10 };
        public int[] Resources { get => resources; private set => resources = value; }
        
        public int Score { get; private set; } = 0;

        private int stars = 0;

        [SerializeField] int waterConsume = 3;
        [SerializeField] int mineConsume = 1;

        [SerializeField] int starBonus = 30;

        public UnityEvent ScoreAdded;

        [Header("Tree")]
        [SerializeField] SpriteRenderer tree;
        [SerializeField] Sprite[] treeSprites;
        [SerializeField] int[] treeScoreThresholds;

        public bool HasEnoughResources => resources[0] >= waterConsume &&
            Resources[1] >= mineConsume;

        public bool Losing => HasEnoughResources &&
            (resources[0] < waterConsume * 2 ||
            resources[1] < mineConsume * 2);

        private void Start()
        {
            ui.UpdateResScores(resources, Score);
            ui.UpdateStar(stars);
        }

        public void AddScore(Resource resource)
        {
            if (resource.isStar)
            {
                Score += starBonus;
                stars += 1;
                ui.UpdateStar(stars);
            }
            else
            {
                Resources[resource.type] += resource.num;
                Score += 1;
            }

            ui.UpdateResScores(resources, Score);

            tree.sprite = DecideTreeSprite();

            if (resource.CompareTag("FinalPoint"))
            {
                ui.ShowGameOver(Score);
            }
        }

        public void ConsumeResource()
        {
            Resources[0] -= waterConsume;
            Resources[1] -= mineConsume;

            ui.UpdateResScores(resources, Score);

            if (!HasEnoughResources) ui.ShowGameOver(Score);
        }

        private Sprite DecideTreeSprite()
        {
            for (int i = 0; i < treeScoreThresholds.Length; i++)
            {
                if (Score <= treeScoreThresholds[i]) return treeSprites[i];
            }
            return treeSprites[treeSprites.Length - 1];
        }
    }
}